package com.example.lenovo.weiyi;

import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.com.ruanmeng.demon.CommonM;
import com.com.ruanmeng.demon.StartTrainM;
import com.com.ruanmeng.utils.CommonUtil;
import com.com.ruanmeng.utils.ImgDataUtil;
import com.com.ruanmeng.utils.Params;
import com.com.ruanmeng.utils.PreferencesUtils;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.rest.Request;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import music.Player;
import nohttp.CallServer;
import nohttp.CustomHttpListener;
import share.Const;
import share.HttpIP;
import yulanpic.ImagePagerActivity;

import static music.Player.needxh;

/**
 * 康复指导  开始锻炼
 */
public class StartTrainActivity extends BaseActivity implements MediaPlayer.OnCompletionListener {

    @BindView(R.id.rlist_jc)
    RecyclerView mRecyclerView;
    @BindView(R.id.imv_showbig)
    ImageView imvShowbig;
    @BindView(R.id.tv_train_content)
    TextView tvTrainContent;
    @BindView(R.id.tv_radio_nowtime)
    TextView tvRadioNowtime;
    @BindView(R.id.music_progress)
    SeekBar musicProgress;
    @BindView(R.id.tv_radio_alltime)
    TextView tvRadioAlltime;
    @BindView(R.id.bt_stoptrain)
    Button btStoptrain;
    @BindView(R.id.refresh_jc)
    SwipeRefreshLayout mRefresh;
    @BindView(R.id.imv_playmusic)
    ImageView imvPlaymusic;
    @BindView(R.id.li_start_video)
    LinearLayout liStartVideo;
    private GalleryAdapter mAdapter;
    List<StartTrainM.UserEvalItemsBean> Temp_list = new ArrayList<>();
    private Player player;
    private Timer mTimer; // 计时器
    int IsPlaying = 0;//0   未播放   1 在播放
    private String video_link;
    private TextView li_srart_null;
    private String pic_big;
    private StartTrainM model;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_start_train);
        ButterKnife.bind(this);
        ChangLayTitle("锻炼内容");
        LayBack();
        init();
        getData();
    }

    public void init() {
        //空
        li_srart_null = (TextView) findViewById(R.id.li_srart_null);
        mRefresh.setColorSchemeResources(R.color.MainColor);
        mRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getData();
            }
        });
        //设置布局管理器
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        mRecyclerView.setLayoutManager(linearLayoutManager);
        //设置适配器
        mAdapter = new GalleryAdapter(StartTrainActivity.this, Temp_list);
        mRecyclerView.setAdapter(mAdapter);
        //关于音乐
        player = new Player(musicProgress);
        needxh = 0;//不需要循环播放
        musicProgress.setOnSeekBarChangeListener(new SeekBarChangeEvent());
        player.mediaPlayer.setOnCompletionListener(this);
    }

    private void getData() {
        Request<String> mRequest = NoHttp.createStringRequest(HttpIP.StartTrain, Const.POST);
        mRequest.addHeader("token", PreferencesUtils.getString(StartTrainActivity.this, "uid"));
        CallServer.getRequestInstance().add(StartTrainActivity.this, 0, mRequest,
                new CustomHttpListener(StartTrainActivity.this, true, StartTrainM.class) {

                    @Override
                    public void doWork(Object data, boolean isOne) {
                        model = ((StartTrainM) data);
                        Temp_list.clear();
                        if (model.getUserEvalItems() != null) {
                            Temp_list.addAll(model.getUserEvalItems());
                        }
                        if (Temp_list.size() == 0) {
                            li_srart_null.setVisibility(View.VISIBLE);
                            mRefresh.setVisibility(View.GONE);
                        } else {
                            li_srart_null.setVisibility(View.GONE);
                            mRefresh.setVisibility(View.VISIBLE);
                            pic_big = HttpIP.Base_IpIMage + Temp_list.get(0).getGuidePic();
                            ImgDataUtil.loadYuanImage(StartTrainActivity.this, HttpIP.Base_IpIMage + Temp_list.get(0).getGuidePic(), imvShowbig);
                            tvTrainContent.setMovementMethod(LinkMovementMethod.getInstance());
                            tvTrainContent.setText(Html.fromHtml(Temp_list.get(0).getEvalText()).toString());
                            video_link = Temp_list.get(0).getGuideMusic();
                            if (!TextUtils.isEmpty(video_link)) {
                                liStartVideo.setVisibility(View.VISIBLE);
                            } else {
                                liStartVideo.setVisibility(View.GONE);
                            }
                        }
                        mAdapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onFinally(JSONObject obj) throws JSONException {
                        super.onFinally(obj);
                        mRefresh.setRefreshing(false);
                    }
                }, true, true);
    }

    /**
     * 结束锻炼
     */
    private void getStopData() {
        //获取当前时间
        SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = sDateFormat.format(new java.util.Date());
        Request<String> mRequest = NoHttp.createStringRequest(HttpIP.Stop_DL, Const.POST);
        mRequest.addHeader("token", PreferencesUtils.getString(StartTrainActivity.this, "uid"));
        mRequest.add("beginTime", getIntent().getStringExtra("starttime"));
        mRequest.add("assessId", model.getAssessId());
        CallServer.getRequestInstance().add(StartTrainActivity.this, 0, mRequest,
                new CustomHttpListener(StartTrainActivity.this, true, CommonM.class) {

                    @Override
                    public void doWork(Object data, boolean isOne) {
                        CommonM model = ((CommonM) data);
                        finish();
                    }

                    @Override
                    public void onFinally(JSONObject obj) throws JSONException {
                        super.onFinally(obj);
                        mRefresh.setRefreshing(false);
                    }
                }, true, true);
    }

    public class GalleryAdapter extends
            RecyclerView.Adapter<GalleryAdapter.ViewHolder> {
        private List<StartTrainM.UserEvalItemsBean> mDatas;

        public GalleryAdapter(Context context, List<StartTrainM.UserEvalItemsBean> datats) {
            mDatas = datats;
        }

        public class ViewHolder extends RecyclerView.ViewHolder {
            public ViewHolder(View arg0) {
                super(arg0);
            }

            ImageView mImg;
            TextView mTxt;
        }

        @Override
        public int getItemCount() {
            return mDatas.size();
        }

        /**
         * 创建ViewHolder
         */
        @Override
        public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
            View view = getLayoutInflater().inflate(R.layout.item_imv, null);

//            View view = mInflater.inflate(R.layout.activity_recycler_item,
//                    viewGroup, false);
            ViewHolder viewHolder = new ViewHolder(view);

            viewHolder.mImg = (ImageView) view
                    .findViewById(R.id.imv);
            return viewHolder;
        }


        /**
         * 设置值
         */
        @Override
        public void onBindViewHolder(final ViewHolder viewHolder, final int i) {
            ImgDataUtil.loadYuanImage(StartTrainActivity.this, HttpIP.Base_IpIMage + mDatas.get(i).getGuidePic(), viewHolder.mImg);
            viewHolder.mImg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    pic_big = HttpIP.Base_IpIMage + mDatas.get(i).getGuidePic();
                    ImgDataUtil.loadYuanImage(StartTrainActivity.this, HttpIP.Base_IpIMage + mDatas.get(i).getGuidePic(), imvShowbig);
                    tvTrainContent.setMovementMethod(LinkMovementMethod.getInstance());
                    tvTrainContent.setText(Html.fromHtml(mDatas.get(i).getEvalText()).toString());
                    video_link = mDatas.get(i).getGuideMusic();
                    if (!TextUtils.isEmpty(video_link)) {
                        liStartVideo.setVisibility(View.VISIBLE);
                    } else {
                        liStartVideo.setVisibility(View.GONE);
                    }
                    //音乐回复默认
//                    if (player != null && player.mediaPlayer != null && player.mediaPlayer.isPlaying()) {
//                        player.pause();
//                    }
                    player.mediaPlayer.reset();
                    musicProgress.setProgress(0);
                    tvRadioNowtime.setText("00:00");
                    tvRadioAlltime.setText("00:00");
                    IsPlaying = 0;
                    imvPlaymusic.setBackgroundResource(R.drawable.zd_play_b);
                }
            });
        }

    }

    /**
     * 关于音乐
     *
     * @param mp
     */
    @Override
    public void onCompletion(MediaPlayer mp) {
        IsPlaying = 0;
        imvPlaymusic.setBackgroundResource(R.drawable.zd_play_b);
        musicProgress.setProgress(100);
    }

    class SeekBarChangeEvent implements SeekBar.OnSeekBarChangeListener {
        int progress;

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress,
                                      boolean fromUser) {
            // 原本是(progress/seekBar.getMax())*player.mediaPlayer.getDuration()
            this.progress = progress * player.mediaPlayer.getDuration()
                    / seekBar.getMax();
            int position = player.mediaPlayer.getCurrentPosition();
            tvRadioNowtime.setText(CommonUtil.stringForTime(position));//当前时间
            int duration = player.mediaPlayer.getDuration();
            tvRadioAlltime.setText(CommonUtil.stringForTime(duration));

        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            // seekTo()的参数是相对与影片时间的数字，而不是与seekBar.getMax()相对的数字
            player.mediaPlayer.seekTo(progress);
        }

    }

    public void playvideo() {
        new Thread(new Runnable() {

            @Override
            public void run() {
                player.playUrl(HttpIP.Base_IpIMage + video_link);
            }
        }).start();
      /*  if (mTimer != null) {
            mTimer.cancel();
            mTimer=null;
        }*/
        if (mTimer == null) {
            mTimer = new Timer();
            mTimer.schedule(timerTask, 0, 1000);
        }
    }

    // 计时器
    TimerTask timerTask = new TimerTask() {

        @Override
        public void run() {
            if (player.mediaPlayer == null)
                return;
            try {
                if (player.mediaPlayer.isPlaying()) {
//                    imvRadioPlay.setBackgroundResource(R.drawable.radio_play);
//                    IsPlaying = 1;
                    handler.sendEmptyMessage(0); // 发送消息
                }
            } catch (Exception o) {
            }
        }

    };

    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            int duration = player.mediaPlayer.getDuration();
            int nowposition = player.mediaPlayer.getCurrentPosition();
            if (duration > 0) {
                tvRadioNowtime.setText(CommonUtil.stringForTime(nowposition));//当前时间
            }
            if (duration == nowposition) {
                if (mTimer != null) {
                    mTimer.cancel();
                }
            }
        }

        ;
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (player != null) {
            player.stop();
            player = null;
        }
        if (mTimer != null) {
            mTimer.cancel();
        }
    }

    @Override
    protected void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        if (player == null) {
            player = new Player(musicProgress);
        }
    }

    public void doClick(View v) {
        switch (v.getId()) {
            case R.id.imv_playmusic:
//                video_link = "http://abv.cn/music/光辉岁月.mp3";
                if (TextUtils.isEmpty(video_link)) {
                    return;
                }
                if (IsPlaying == 0) {
//                    if (player.mediaPlayer.getCurrentPosition() == 1) {
                        playvideo();
//                        CommonUtil.showToask(StartTrainActivity.this, "play");
//                    } else {
//                        player.mediaPlayer.start();
////                        CommonUtil.showToask(StartTrainActivity.this, "start");
//                    }
                    IsPlaying = 1;
                    imvPlaymusic.setBackgroundResource(R.drawable.zd_suspended_b);

                } else {
                    IsPlaying = 0;
                    imvPlaymusic.setBackgroundResource(R.drawable.zd_play_b);
                    player.mediaPlayer.pause();
                }
                break;
            case R.id.bt_stoptrain://结束锻炼
                getStopData();
                break;
            case R.id.imv_showbig:
                Params.piccontent = tvTrainContent.getText().toString();
                YuLanPic(pic_big);
                break;
        }
    }

    /**
     * 预览图片
     */
    public void YuLanPic(String url) {
        String[] aStrings = new String[1];
        aStrings[0] = url;
        Intent intent1 = new Intent(StartTrainActivity.this,
                ImagePagerActivity.class); //
        // 图片url,为了演示这里使用常量，一般从数据库中或网络中获取
        intent1.putExtra(ImagePagerActivity.EXTRA_IMAGE_URLS, aStrings);
        intent1.putExtra(ImagePagerActivity.EXTRA_IMAGE_INDEX, 0);
        startActivity(intent1);
    }
}
